class Game {
  constructor() {
    this.canvas = document.getElementById('gameCanvas');
    this.ctx = this.canvas.getContext('2d');

    // 设置画布大小
    this.resizeCanvas();
    window.addEventListener('resize', () => this.resizeCanvas());

    // 初始化控制器
    this.moveJoystick = new VirtualJoystick('move-joystick');

    // 创建玩家坦克
    this.player = new Tank(this.canvas.width / 2, this.canvas.height / 2);

    // 加载游戏资源
    this.loadAssets();

    // 添加地图设置
    this.mapTileSize = 64;
    this.mapWidth = Math.ceil(window.innerWidth / this.mapTileSize);
    this.mapHeight = Math.ceil(window.innerHeight / this.mapTileSize);
    this.createMap();

    // 添加游戏状态
    this.gameState = {
      score: 0,
      level: 1,
      isGameOver: false
    };

    // 添加游戏元素
    this.bullets = [];
    this.enemies = [];
    this.base = {
      x: this.canvas.width / 2,
      y: this.canvas.height - 100,
      size: 64,
      health: 100
    };

    // 初始化敌人
    this.spawnEnemies();

    // 添加事件监听
    document.getElementById('fireBtn').addEventListener('click', () => this.playerFire());

    // 添加键盘控制
    this.keys = {
      fire: false
    };

    document.addEventListener('keydown', (e) => {
      if (e.code === 'Space') {
        this.playerFire();
      }
    });

    // 添加触摸事件监听
    document.getElementById('fireBtn').addEventListener('touchstart', (e) => {
      e.preventDefault();
      this.playerFire();
    });

    // 开始游戏循环
    this.gameLoop();
  }

  resizeCanvas() {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }

  update() {
    if (this.gameState.isGameOver) return;

    // 更新玩家
    const moveInput = this.moveJoystick.getInput();
    this.player.update(moveInput, null, this.map, this.mapTileSize);

    // 更新敌人
    this.updateEnemies();

    // 更新子弹
    this.updateBullets();

    // 检查关卡完成
    if (this.enemies.length === 0) {
      this.gameState.level++;
      this.spawnEnemies();
    }
  }

  updateEnemies() {
    this.enemies.forEach(enemy => {
      // 简单的AI：朝向玩家或基地
      const target = Math.random() < 0.7 ? this.player : this.base;
      const dx = target.x - enemy.x;
      const dy = target.y - enemy.y;

      // 计算到目标的距离
      const distanceToTarget = Math.sqrt(dx * dx + dy * dy);

      // 如果碰到障碍物，尝试随机改变方向
      if (enemy.isStuck) {
        enemy.rotation += (Math.random() - 0.5) * Math.PI / 2;
        enemy.isStuck = false;
      } else {
        // 正常朝向目标
        const targetRotation = Math.atan2(dy, dx);
        // 平���转向
        const rotationDiff = targetRotation - enemy.rotation;
        enemy.rotation += Math.sign(rotationDiff) * Math.min(Math.abs(rotationDiff), 0.05);
      }

      // 随机移动和开火
      if (Math.random() < 0.02 && distanceToTarget < 400) {  // 只在一定距离内开火
        const bullet = enemy.fire();
        if (bullet) this.bullets.push(bullet);
      }

      // 移动
      const moveInput = {
        x: Math.cos(enemy.rotation) * 0.5,
        y: Math.sin(enemy.rotation) * 0.5
      };

      // 记录上一次位置
      const lastX = enemy.x;
      const lastY = enemy.y;

      enemy.update(moveInput, { x: 0, y: 0 }, this.map, this.mapTileSize);

      // 检查是否卡住
      if (Math.abs(enemy.x - lastX) < 0.1 && Math.abs(enemy.y - lastY) < 0.1) {
        enemy.isStuck = true;
      }
    });
  }

  updateBullets() {
    for (let i = this.bullets.length - 1; i >= 0; i--) {
      const bullet = this.bullets[i];
      bullet.update();

      // 检查子弹碰撞
      if (this.checkBulletCollision(bullet)) {
        this.bullets.splice(i, 1);
        continue;
      }

      // 检查子弹是否出界
      if (bullet.x < 0 || bullet.x > this.canvas.width ||
        bullet.y < 0 || bullet.y > this.canvas.height) {
        this.bullets.splice(i, 1);
      }
    }
  }

  checkBulletCollision(bullet) {
    // 检查墙壁碰撞
    const tileX = Math.floor(bullet.x / this.mapTileSize);
    const tileY = Math.floor(bullet.y / this.mapTileSize);
    if (this.map[tileY]?.[tileX] === 1) return true;

    // 检查坦克碰撞
    if (bullet.team === 'player') {
      // 玩家子弹检查敌人
      for (let i = this.enemies.length - 1; i >= 0; i--) {
        const enemy = this.enemies[i];
        if (this.checkCollision(bullet, enemy)) {
          if (enemy.takeDamage(bullet.damage)) {
            this.gameState.score += enemy.team === 'boss' ? 1000 : 100;
            this.enemies.splice(i, 1);
          }
          return true;
        }
      }
    } else {
      // 敌人子弹检查玩家和基地
      if (this.checkCollision(bullet, this.player)) {
        if (this.player.takeDamage(bullet.damage)) {
          this.gameOver();
        }
        return true;
      }
      if (this.checkCollision(bullet, this.base)) {
        this.base.health -= bullet.damage;
        if (this.base.health <= 0) {
          this.gameOver();
        }
        return true;
      }
    }
    return false;
  }

  checkCollision(bullet, target) {
    const dx = bullet.x - target.x;
    const dy = bullet.y - target.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    return distance < (bullet.size + target.size) / 2;
  }

  gameOver() {
    this.gameState.isGameOver = true;
    // 显示游戏结束界面
    const gameOverDiv = document.createElement('div');
    gameOverDiv.className = 'game-over';
    gameOverDiv.innerHTML = `
      <h2>游戏结束</h2>
      <p>得分: ${this.gameState.score}</p>
      <p>关卡: ${this.gameState.level}</p>
      <button onclick="location.reload()">重新开始</button>
    `;
    document.body.appendChild(gameOverDiv);
  }

  draw() {
    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 绘制地图
    for (let y = 0; y < this.mapHeight; y++) {
      for (let x = 0; x < this.mapWidth; x++) {
        const tileX = x * this.mapTileSize;
        const tileY = y * this.mapTileSize;

        // 绘制地面
        this.ctx.drawImage(this.groundTile, tileX, tileY, this.mapTileSize, this.mapTileSize);

        // 绘制墙壁
        if (this.map[y][x] === 1) {
          this.ctx.drawImage(this.wallTile, tileX, tileY, this.mapTileSize, this.mapTileSize);
        }
      }
    }

    // 绘制基地
    this.ctx.fillStyle = '#2ecc71';
    this.ctx.fillRect(
      this.base.x - this.base.size / 2,
      this.base.y - this.base.size / 2,
      this.base.size,
      this.base.size
    );

    // 绘制敌人
    this.enemies.forEach(enemy => enemy.draw(this.ctx));

    // 绘制子弹
    this.bullets.forEach(bullet => bullet.draw(this.ctx));

    // 绘制玩家坦克
    this.player.draw(this.ctx);

    // 绘制UI
    this.drawUI();
  }

  drawUI() {
    this.ctx.fillStyle = '#fff';
    this.ctx.font = '20px Arial';
    this.ctx.fillText(`得分: ${this.gameState.score}`, 20, 30);
    this.ctx.fillText(`���卡: ${this.gameState.level}`, 20, 60);
    this.ctx.fillText(`生命: ${this.player.health}`, 20, 90);
    this.ctx.fillText(`基地: ${this.base.health}`, 20, 120);
  }

  gameLoop() {
    this.update();
    this.draw();
    requestAnimationFrame(() => this.gameLoop());
  }

  loadAssets() {
    // 创建临时的坦克图片
    const tankCanvas = document.createElement('canvas');
    tankCanvas.width = 48;
    tankCanvas.height = 48;
    const tankCtx = tankCanvas.getContext('2d');

    // 绘制坦克主体
    tankCtx.fillStyle = '#3498db';
    tankCtx.fillRect(0, 0, 48, 48);
    // 绘制炮管
    tankCtx.fillStyle = '#2980b9';
    tankCtx.fillRect(20, 0, 8, 48);

    // 将临时画布转换为图片源
    this.player.image.src = tankCanvas.toDataURL();

    // 创建临时的地面贴图
    const groundCanvas = document.createElement('canvas');
    groundCanvas.width = 64;
    groundCanvas.height = 64;
    const groundCtx = groundCanvas.getContext('2d');

    // 绘制地面
    groundCtx.fillStyle = '#95a5a6';
    groundCtx.fillRect(0, 0, 64, 64);
    groundCtx.strokeStyle = '#7f8c8d';
    groundCtx.strokeRect(0, 0, 64, 64);

    this.groundTile = new Image();
    this.groundTile.src = groundCanvas.toDataURL();

    // 创建临时的墙壁贴图
    const wallCanvas = document.createElement('canvas');
    wallCanvas.width = 64;
    wallCanvas.height = 64;
    const wallCtx = wallCanvas.getContext('2d');

    // 绘制墙壁
    wallCtx.fillStyle = '#e74c3c';
    wallCtx.fillRect(0, 0, 64, 64);
    wallCtx.strokeStyle = '#c0392b';
    wallCtx.strokeRect(0, 0, 64, 64);

    this.wallTile = new Image();
    this.wallTile.src = wallCanvas.toDataURL();
  }

  createMap() {
    this.map = [];
    for (let y = 0; y < this.mapHeight; y++) {
      this.map[y] = [];
      for (let x = 0; x < this.mapWidth; x++) {
        // 在地图边缘创建墙壁
        if (x === 0 || x === this.mapWidth - 1 || y === 0 || y === this.mapHeight - 1) {
          this.map[y][x] = 1; // 1 表示墙
        } else {
          // 随机生成一些障碍物
          this.map[y][x] = Math.random() < 0.1 ? 1 : 0;
        }
      }
    }
  }

  spawnEnemies() {
    // 清空现有敌人
    this.enemies = [];

    // 生成普通敌人
    for (let i = 0; i < this.gameState.level * 3; i++) {
      const x = Math.random() * (this.canvas.width - 100) + 50;
      const y = Math.random() * 200 + 50;
      this.enemies.push(new Tank(x, y, 'enemy'));
    }

    // 生成首领（每5关出现一次）
    if (this.gameState.level % 5 === 0) {
      const boss = new Tank(this.canvas.width / 2, 100, 'boss');
      boss.health = 200;
      boss.size = 64;
      this.enemies.push(boss);
    }
  }

  playerFire() {
    const bullet = this.player.fire();
    if (bullet) {
      this.bullets.push(bullet);

      // 可以添加开火音效
      // this.playSound('fire');
    }
  }
}

// 当页面加载完成后启动游戏
window.addEventListener('load', () => {
  new Game();
}); 